package com.tybbank.Fragment;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;
import com.taobao.library.VerticalBannerView;
import com.tybbank.Activity.BuyGoldActivity;
import com.tybbank.Activity.IntoActivity;
import com.tybbank.Activity.NewsListActivity;
import com.tybbank.Activity.RecordActivity;
import com.tybbank.Activity.RollOutOneActivity;
import com.tybbank.Activity.RollOutTwoActivity;
import com.tybbank.Activity.SellGoldActivity;
import com.tybbank.Activity.SharedSDKActivity;
import com.tybbank.Activity.TaoCanActivity;
import com.tybbank.Activity.TiSuActivity;
import com.tybbank.Adapter.SampleAdapter;
import com.tybbank.Bean.HomeBean;
import com.tybbank.Bean.Modd;
import com.tybbank.Bean.Model01;
import com.tybbank.Bean.RollOutOneBean;
import com.tybbank.Login.LoginActivity;
import com.tybbank.MyApplication;
import com.tybbank.R;
import com.tybbank.Utils.Constant;
import com.tybbank.Utils.GlideImageLoader;
import com.tybbank.Utils.MD5Utils;
import com.tybbank.Utils.MyDialogUtils;
import com.tybbank.Utils.logUtilssss;
import com.tybbank.web.WebActivity;
import com.uuzuche.lib_zxing.activity.CodeUtils;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.SortedMap;
import java.util.TreeMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import okhttp3.Call;

import static android.app.Activity.RESULT_OK;

/**
 * Created by Administrator on 2018/5/31 0031.
 */

public class HomeFragment extends Fragment {

    @BindView(R.id.home_banner)
    Banner homeBanner;
    @BindView(R.id.iv_news)
    ImageView ivNews;
    @BindView(R.id.vbv_chuizhi)
    VerticalBannerView vbvChuizhi;
    @BindView(R.id.tv_tisu)
    TextView tvTisu;
    @BindView(R.id.ll_tisu_list)
    LinearLayout llTisuList;
    @BindView(R.id.tv_dingqi)
    TextView tvDingqi;
    @BindView(R.id.ll_dingqi_list)
    LinearLayout llDingqiList;
    @BindView(R.id.iv_register)
    ImageView ivRegister;
    @BindView(R.id.ll_into)
    LinearLayout llInto;
    @BindView(R.id.ll_Roll_out)
    LinearLayout llRollOut;
    @BindView(R.id.ll_speed_up)
    LinearLayout llSpeedUp;
    @BindView(R.id.ll_buy)
    LinearLayout llBuy;
    @BindView(R.id.ll_sell)
    LinearLayout llSell;
    @BindView(R.id.ll_shard_sdk)
    LinearLayout llShardSdk;
    @BindView(R.id.iv_flicking)
    ImageView ivFlicking;
    Unbinder unbinder;
    @BindView(R.id.ll_news)
    LinearLayout llNews;
    @BindView(R.id.ll_shop_car)
    LinearLayout llShopCar;
    @BindView(R.id.iv_kefu)
    ImageView ivKefu;
    @BindView(R.id.tv_zengzhi)
    TextView tvZengzhi;
    @BindView(R.id.ll_zengzhi_list)
    LinearLayout llZengzhiList;
    @BindView(R.id.ptr_scroll_view)
    PullToRefreshScrollView ptrScrollView;
    private Intent intent;
    private String current = "";
    private String abc_coin = "";

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.activity_home, container, false);
        unbinder = ButterKnife.bind(this, view);
        ptrScrollView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
        ptrScrollView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ScrollView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ScrollView> refreshView) {
                init();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ScrollView> refreshView) {
                init();
            }
        });
        init();
        return view;
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            init();
        }
    }

    private void init() {
        String time = MD5Utils.getTime();
        SortedMap<String, String> parameters = new TreeMap<String, String>(
                new Comparator<String>() {
                    public int compare(String obj1, String obj2) {
                        // 降序排序
                        return obj1.compareTo(obj2);
                    }
                });
        parameters.put("uuid", MyApplication.uuid);
        parameters.put("token", MyApplication.token);
        parameters.put("TimeStamp", time);
        String sign = MD5Utils.createSign(parameters);
        final Dialog dialog = MyDialogUtils.createLoadingDialog(getActivity(), getString(R.string.loading));
        dialog.show();
        OkHttpUtils
                .post()
                .url(Constant.index)
                .addParams("uuid", MyApplication.uuid)
                .addParams("token", MyApplication.token)
                .addParams("TimeStamp", time)
                .addParams("Sign", sign)
                .build()
                .execute(new StringCallback() {
                    @SuppressLint("WrongConstant")
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        e.printStackTrace();
                        dialog.dismiss();
                        ptrScrollView.onRefreshComplete();
                        Toast.makeText(getActivity(), getString(R.string.error), Toast.LENGTH_SHORT).show();
                        return;
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        logUtilssss.e("TAG首页" + response.toString());
                        ptrScrollView.onRefreshComplete();
                        dialog.dismiss();
                        string(response);
                    }

                    @SuppressLint("WrongConstant")
                    private void string(String json) {
                        try {
                            HomeBean enterBean = new Gson().fromJson(json, new TypeToken<HomeBean>() {
                            }.getType());
                            int status = enterBean.getCode();
                            if (status == 1011) {
                                HomeBean<HomeBean> ent = new Gson().fromJson(json, new TypeToken<HomeBean<HomeBean>>() {
                                }.getType());
                                current = enterBean.getCurrent();
                                abc_coin = enterBean.getAbc_coin();
                                tvTisu.setText(enterBean.getCurrent());
                                tvDingqi.setText(enterBean.getRegular());
                                tvZengzhi.setText(enterBean.getIncrement());
                                List<HomeBean.GonggaoBean> gonggao = ent.getGonggao();
                                List<HomeBean.LunboBean> lunbo = ent.getLunbo();
                                initView(gonggao, lunbo);
                            } else if (status == 1004) {
                                Intent intent = new Intent(getActivity(), LoginActivity.class);
                                startActivity(intent);
                                return;
                            } else {
                                Toast.makeText(getActivity(), enterBean.getMsg(), Toast.LENGTH_SHORT).show();
                            }

                        } catch (Exception e) {

                        }
                    }
                });
    }

    private void initView(List<HomeBean.GonggaoBean> gonggao, List<HomeBean.LunboBean> lunbo) {
        List<String> list = new ArrayList<>();
        final List<Modd> listt = new ArrayList<>();
        if (lunbo.size() != 0) {
            for (int i = 0; i < lunbo.size(); i++) {
                list.add(lunbo.get(i).getPath());
                listt.add(new Modd(lunbo.get(i).getId(), lunbo.get(i).getPath()));
            }
            homeBanner.setImages(list);
            homeBanner.setImageLoader(new GlideImageLoader("HomeFragment"));
            homeBanner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
            homeBanner.setIndicatorGravity(BannerConfig.CENTER);
            homeBanner.startAutoPlay();
            homeBanner.start();
        }
        // chuizhi
        List<Model01> lista = new ArrayList<>();
        if (gonggao.size() == 0) {
            return;
        } else {
            if (gonggao.size() == 1) {
                for (int i = 0; i < gonggao.size(); i++) {
                    HomeBean.GonggaoBean newsBean = gonggao.get(i);
                    lista.add(new Model01(newsBean.getTitle(), newsBean.getPath()));
                    lista.add(new Model01(newsBean.getTitle(), newsBean.getPath()));
                }
            } else {
                for (int i = 0; i < gonggao.size(); i++) {
                    HomeBean.GonggaoBean newsBean = gonggao.get(i);
                    lista.add(new Model01(newsBean.getTitle(), newsBean.getPath()));
                }
            }
            SampleAdapter adapter = new SampleAdapter(lista, getActivity());
            vbvChuizhi.setAdapter(adapter);
            vbvChuizhi.start();
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick({R.id.ll_zengzhi_list, R.id.iv_kefu, R.id.iv_register, R.id.ll_news, R.id.ll_shop_car, R.id.iv_flicking, R.id.ll_tisu_list, R.id.ll_dingqi_list, R.id.ll_into, R.id.ll_Roll_out, R.id.ll_speed_up, R.id.ll_buy, R.id.ll_sell, R.id.ll_shard_sdk})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_kefu:  //客服
                intent = new Intent(getActivity(), WebActivity.class);
                intent.putExtra("title", getString(R.string.kefu));
                intent.putExtra("url", Constant.KEFU);
                getActivity().startActivity(intent);
                break;
            case R.id.ll_news:  //新闻
                // Intent  intent = new Intent(getActivity(), NoticeActivity.class);
                intent = new Intent(getActivity(), NewsListActivity.class);
                getActivity().startActivity(intent);
                break;
            case R.id.ll_shop_car:  // 商城
                logUtilssss.toast(getActivity(), getString(R.string.qidai));
                break;
            case R.id.iv_flicking:      //扫一扫
                Toast.makeText(getActivity(), getString(R.string.weihu), Toast.LENGTH_SHORT).show();
//                intent = new Intent(getActivity(), CaptureActivity.class);
//                startActivityForResult(intent, 600);
                break;
            case R.id.ll_tisu_list: //提速值记录
                intent = new Intent(getActivity(), RecordActivity.class);
                intent.putExtra("type", "2");
                intent.putExtra("classify", "0");
                intent.putExtra("title", getString(R.string.jilu));
                getActivity().startActivity(intent);
                break;
            case R.id.ll_dingqi_list:   //定期值记录
//                intent = new Intent(getActivity(), DingQiListActivity.class);
//                getActivity().startActivity(intent);
                intent = new Intent(getActivity(), RecordActivity.class);
                intent.putExtra("type", "1");
                intent.putExtra("classify", "0");
                intent.putExtra("title", getString(R.string.jilu));
                getActivity().startActivity(intent);
                break;
            case R.id.ll_zengzhi_list:   //增值记录
                intent = new Intent(getActivity(), RecordActivity.class);
                intent.putExtra("type", "5");
                intent.putExtra("classify", "0");
                intent.putExtra("title", getString(R.string.jilu));
                getActivity().startActivity(intent);
                break;
            case R.id.ll_into:  //转入
                intent = new Intent(getActivity(), IntoActivity.class);
                getActivity().startActivity(intent);
                break;
            case R.id.ll_Roll_out://转出 OTC
                Toast.makeText(getActivity(), getString(R.string.weihu), Toast.LENGTH_SHORT).show();
//                intent = new Intent(getActivity(), RollOutOneActivity.class);
//                startActivityForResult(intent, 200);
                break;
            case R.id.ll_speed_up://提速
                intent = new Intent(getActivity(), TiSuActivity.class);
                intent.putExtra("abc_coin", abc_coin);
                intent.putExtra("current", current);
                startActivityForResult(intent, 200);
                break;
            case R.id.ll_buy:// 充币
                intent = new Intent(getActivity(), BuyGoldActivity.class);
                startActivityForResult(intent, 200);
                break;
            case R.id.ll_sell://提币
                intent = new Intent(getActivity(), SellGoldActivity.class);
                startActivityForResult(intent, 200);
                break;
            case R.id.iv_register://
                intent = new Intent(getActivity(), TaoCanActivity.class);
                startActivityForResult(intent, 300);
                break;
            case R.id.ll_shard_sdk://分享
                intent = new Intent(getActivity(), SharedSDKActivity.class);
                getActivity().startActivity(intent);
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 300) {
            init();
        } else if (requestCode == 200 && resultCode == RESULT_OK) {
            init();
        } else if (requestCode == 600) {
            if (null != data) {
                Bundle bundle = data.getExtras();
                if (bundle == null) {
                    return;
                }
                if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                    String result = bundle.getString(CodeUtils.RESULT_STRING);
                    if (result.length() == 0) {
                        Toast.makeText(getActivity(), getString(R.string.saomiaonull), Toast.LENGTH_SHORT).show();
                        return;
                    } else if (result.length() >= 4 && result.substring(0, 4).equals("http")) {
                        Uri uri = Uri.parse(result);
                        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                        getActivity().startActivity(intent);
                    } else {
                        initdata(result);
                    }
                } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
                    Toast.makeText(getActivity(), getString(R.string.jiexierror), Toast.LENGTH_SHORT).show();
                }
            } else {
                //Toast.makeText(getActivity(), "解析失败", Toast.LENGTH_SHORT).show();
            }

        }
    }

    private void initdata(String result) {
        String time = MD5Utils.getTime();
        SortedMap<String, String> parameters = new TreeMap<String, String>(
                new Comparator<String>() {
                    public int compare(String obj1, String obj2) {
                        // 降序排序
                        return obj1.compareTo(obj2);
                    }
                });
        parameters.put("uuid", MyApplication.uuid);
        parameters.put("token", MyApplication.token);
        parameters.put("type", "1");
        parameters.put("account", result);
        parameters.put("TimeStamp", time);
        String sign = MD5Utils.createSign(parameters);
        final Dialog dialog = MyDialogUtils.createLoadingDialog(getActivity(), getString(R.string.loading));
        dialog.show();
        OkHttpUtils
                .post()
                .url(Constant.verify_identity)
                .addParams("uuid", MyApplication.uuid)
                .addParams("token", MyApplication.token)
                .addParams("type", "1")
                .addParams("account", result)
                .addParams("TimeStamp", time)
                .addParams("Sign", sign)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        e.printStackTrace();
                        dialog.dismiss();
                        logUtilssss.toasteero(getActivity());
                        return;
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        logUtilssss.e("TAG根据手机号或UUID查询用户是否存在" + response.toString());
                        dialog.dismiss();
                        string(response);
                    }

                    private void string(String json) {
                        try {
                            RollOutOneBean enterBean = new Gson().fromJson(json, new TypeToken<RollOutOneBean>() {
                            }.getType());
                            int status = enterBean.getCode();
                            if (status == 1011) {
                                RollOutOneBean<RollOutOneBean.DataBean> enter = new Gson().fromJson(json, new TypeToken<RollOutOneBean<RollOutOneBean.DataBean>>() {
                                }.getType());
                                intent = new Intent(getActivity(), RollOutTwoActivity.class);    // 输入姓名验证是否存在 跳往转账页面
                                intent.putExtra("etAccount", enter.getData().getAccount());
                                intent.putExtra("uuid", enter.getData().getUuid());
                                startActivityForResult(intent, 200);
                            } else if (status == 1004) {
                                intent = new Intent(getActivity(), LoginActivity.class);
                                startActivity(intent);
                                return;
                            } else {
                                logUtilssss.toast(getActivity(), enterBean.getMsg());
                            }
                        } catch (Exception e) {
                            logUtilssss.toasteero(getActivity());
                        }

                    }
                });
    }


}
